<template>
  <div class="paper-wrapper container">
    <div class="paper-left">
      <div class="big-title">{{ examTitle }}</div>
      <div class="paper-question">
        <TestQuestion
          v-for="item in topicList"
          :key="item.id"
          :question="item"
          :qIndex="topicIndex + 1"
          :qType="item.question_type"
          :qScore="topicInfo.score"
          :is_border="false"
          :is_collected="false"
        ></TestQuestion>
      </div>
      <TestPagination @prev="changeTopicPrev" @next="changeTopicNext"></TestPagination>
    </div>
    <div class="paper-right">
      <TestSheet
        @submit="handleSubmitExam"
        @click="handleTopicJump"
        :disabled="disabled"
      ></TestSheet>
    </div>
  </div>
</template>

<script>
import TestQuestion from '../components/test-question'
import TestSheet from '../components/test-sheet'
import TestPagination from '../components/test-pagination'
import { mapState, mapGetters } from 'vuex'
export default {
  components: {
    TestQuestion,
    TestSheet,
    TestPagination
  },
  data() {
    return {
      topicList: [],
      topicCurrentAnswer: '',
      topicLoading: true,
      studentExamTime: 0, // 学生考试用时
      studentExamTimer: null,
      examId: 0, // 试卷id
      examTitle: '', // 试卷标题
      examUniqueCode: '', // 试卷唯一标识
      examTime: null,
      disabled: false,

      cutScreenNumber: 0, // 切屏次数
      cutScreenVerify: 0 // 切屏验证次数
    }
  },
  computed: {
    ...mapState({
      topicIndex: state => state.exam.topic_index,
      topicId: state => state.exam.topic_id,
      testAnswer: state => state.exam.test_answer,
      testDuration: state => state.exam.test_duration,
      projectconfigData: state => state.projectSetting.projectconfigData
    }),
    ...mapGetters({
      topicInfo: 'exam/topic_info'
    }),
    faceVerifyStatus() {
      if (!this.$util.isEmpty(this.$route.query.cid)) return false
      if (!this.$util.isEmpty(this.$route.query.s)) return false
      return false
    }
  },
  watch: {
    topicIndex() {
      this.getExamTopic(this.topicId)
    }
  },
  created() {
    this.getPaperInit()
  },
  mounted() {
    // 绑定页面内容可见或被隐藏时
    document.addEventListener('visibilitychange', this.onPageVisibility)
  },
  methods: {
    // 获取试卷基础信息
    getPaperInit() {
      const _this = this
      _this.$api.getExamPaperBase(
        {
          paper_id: this.$route.query.id
        },
        res => {
          const { data } = res
          _this.examId = data.id
          _this.examTime = data.total_time
          _this.examTitle = data.title
          _this.examUniqueCode = data.unique_code
          _this.cutScreenVerify = data.screen_cut // 设置切屏次数
          _this.$store.dispatch('exam/SET_TEST_INIT', data)
          // 请求试题
          _this.getExamTopic(this.topicId)
          if (_this.examTime > 0) {
            _this.$store.commit('exam/SET_TEST_DURATION', _this.examTime * 60)
          }
          _this.startTime() // 开始倒计时
        }
      )
    },
    // 获取试题
    async getExamTopic(id) {
      const _this = this
      _this.palyRef = ''
      _this.$api.getExamPaperTopic(
        {
          topic_id: id,
          paper_id: this.$route.query.id
        },
        res => {
          _this.topicList = res.data
          _this.setTopicCollected()
        }
      )
    },
    // 试题上一题
    changeTopicPrev() {
      this.$store.commit('exam/SET_TOPIC_PREV')
    },
    // 试题下一题
    changeTopicNext() {
      this.$store.commit('exam/SET_TOPIC_NEXT')
    },
    // 设置试题收藏默认状态
    setTopicCollected() {
      const topic = this.topicList.find(item => item.id == this.topicId)
      this.$store.commit('exam/SET_TOPIC_COLLECTED', topic.collected)
    },
    // 提交考试答案
    handleSubmitExam() {
      const _this = this
      _this.handleSubmit()
    },
    async handleSubmit() {
      const _this = this
      _this.disabled = true
      _this.clearTimer()
      await _this.handleAnswerEmpty()
      await _this.handleExamTime()
      const query = {
        paper_id: _this.$route.query.id,
        unique_code: _this.examUniqueCode,
        answer_data: JSON.stringify(_this.testAnswer),
        time_takes: _this.studentExamTime,
        course_id: _this.$util.isDef(_this.$route.query.cid) ? _this.$route.query.cid : 0, // 课程考试
        is_assign: _this.$util.isDef(_this.$route.query.assign) ? _this.$route.query.assign : 0 // 指派考试
      }
      
      _this.$api.postExamPaperAnswer(
        query,
        res => {
          _this.$message.success(res.msg)
          // 3 公开考试 4 套卷练习 5 课程考试 6 派发考试
          let type = 0
          if(_this.$util.isDef(_this.$route.query.cid)) {
            type = 5
          } else if(_this.$util.isDef(_this.$route.query.assign)) {
            type = 6
          } else {
            type = 3
          }
          setTimeout(() => {
            _this.$router.replace({
              path: '/exam/paper/parsing',
              query: {
                id: res.data.id,
                type: type
              }
            })
            this.disabled = false
          }, 300)
        },
        error => {
          _this.$message.error(error.msg)
          this.disabled = false
        }
      )
    },
    // 答题卡
    handleTopicJump(index) {
      this.$store.commit('exam/SET_TOPIC_CURRENT', index)
    },
    // 处理答案的空数据
    handleAnswerEmpty() {
      const _this = this
      _this.testAnswer.forEach((parts, j) => {
        if (this.$util.isEmpty(parts.data)) return _this.testAnswer.splice(j, 1)
        parts.data.forEach((item, index) => {
          // 多选/不定项
          if (_this.$util.inArray(item.question_type, [3, 4])) {
            // 多选数组为空删除答案
            if (this.$util.isEmpty(item.answer)) parts.data.splice(index, 1)
          }
          // 填空题/简答题
          else if (_this.$util.inArray(item.question_type, [5, 8])) {
            // 数组的每一项都为空时返回true
            let topic = item.answer.every(topic => topic == '')
            // 删除答案为空数据
            if (topic) parts.data.splice(index, 1)
          }
        })
      })
    },
    // 开始考试的时间
    startTime() {
      const _this = this
      _this.examTime == 0 ? _this.changeTimepiece() : _this.changeCountdown()
    },
    // 正计时
    changeTimepiece() {
      const _this = this
      let seconds = _this.testDuration
      _this.studentExamTimer = setInterval(() => {
        seconds++
        _this.$store.commit('exam/SET_TEST_DURATION', seconds)
      }, 1000)
    },
    // 倒计时
    changeCountdown() {
      const _this = this
      // 后台返回的时分钟数，转为秒
      let seconds = _this.testDuration
      // 倒计时
      _this.studentExamTimer = setInterval(() => {
        seconds--
        _this.$store.commit('exam/SET_TEST_DURATION', seconds)
        // 倒计时结束
        if (seconds <= 0) {
          return _this.changeCountdownEnd()
        }
      }, 1000)
    },
    // 考试用时
    handleExamTime() {
      const _this = this
      if (_this.examTime == 0) {
        _this.studentExamTime = _this.testDuration
      } else {
        _this.studentExamTime = _this.examTime * 60 - _this.testDuration
      }
    },
    // 倒计时结束
    changeCountdownEnd() {
      // 提交答案
      this.handleSubmitExam()
    },
    // 清除定时器
    clearTimer() {
      if (this.studentExamTimer) {
        // 清除定时器
        clearInterval(this.studentExamTimer)
        this.studentExamTimer = null
      }
    },
    // 监听页面显示隐藏
    onPageVisibility() {
      let visibility = document.visibilityState
      if (visibility == 'visible') {
        if (this.cutScreenVerify == 0) return
        // 切换次数大于验证次数时自动提交试卷
        if (this.cutScreenNumber > this.cutScreenVerify) {
          this.$message.warning(
            `你已经切换离开考试页面超过${this.cutScreenVerify}次系统将自动提交答卷！`
          )
          setTimeout(() => {
            // 提交答案
            this.handleSubmitExam()
          }, 2500)
        }
        // 切换次数等于验证次数时提示用户
        if (this.cutScreenNumber == this.cutScreenVerify) {
          this.$messageBox
            .confirm(
              `你已经切换离开考试页面${this.cutScreenNumber}次，如果超过${this.cutScreenVerify}次系统会自动提交答卷，请认真作答！`,
              {
                title: '警告',
                confirmButtonText: '知道了',
                showCancelButton: false,
                distinguishCancelAndClose: true,
                closeOnPressEscape: false,
                closeOnClickModal: false
              }
            )
            .then(() => {})
            .catch(() => {})
        }
      } else if (visibility == 'hidden') {
        this.cutScreenNumber++
      }
    }
  },
  destroyed() {
    // 销毁页面时初始化vuex的状态
    this.$store.commit('exam/SET_TEST_STATE_DEFAULT')
  },
  beforeDestroy() {
    clearInterval(this.studentExamTimer)
    this.studentExamTimer = null
    // 移除页面内容可见或被隐藏时
    document.removeEventListener('visibilitychange', this.onPageVisibility)
  }
}
</script>

<style lang="scss" scoped>
.paper-wrapper {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-top: 10px;
  .paper-left {
    width: 890px;
    background-color: #ffffff;
  }
  .big-title {
    padding: 18px 0;
    font-size: 15px;
    font-weight: 500;
    color: #303133;
    text-align: center;
    border-bottom: 1px solid $border-color-divider;
  }
  .paper-question {
    padding: 5px 20px 20px;
  }
  .paper-right {
    width: 300px;
    background-color: #ffffff;
  }
}
</style>
